<template>
  <div class="container">
    <div>
      <input type="checkbox" :checked="isSelectAll" @change="selectAllItems" />
      <span>已完成{{ selectCount }}/全部{{ todoList.length }}</span>
    </div>
    <div>
      <el-button type="danger" size="small" @click="removeCompleteItems">清除已完成任务</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, computed, watch, ref } from 'vue';
import { TodoItemModel } from '@/type-scripts/todo-model';
export default defineComponent({
  name: 'Footer',
  props: {
    todoList: {
      // 转换成具体的类型
      type: Array as () => Array<TodoItemModel>,
      required: true,
    },
  },
  setup(props) {
    let isSelectAll = ref(false);

    // 计算已完成的数量
    const selectCount = computed(() => {
      return props.todoList.reduce(
        (pre: number, todo: TodoItemModel, index: number) => pre + (todo.isComplete ? 1 : 0),
        0
      );
    });
    // 监控已完成数量，设置全选状态
    watch(selectCount, (newData, oldData) => {
      if (newData == 0) {
        isSelectAll.value = false;
        return;
      }
      if (newData == props.todoList.length) {
        isSelectAll.value = true;
      } else {
        isSelectAll.value = false;
      }
    });

    // 全选与取消全选
    let selectAllItems = (changeEvent: any) => {
      // 获取当前checkbox是否选中
      let checked = changeEvent.target.checked;
      props.todoList.forEach((todoItem: TodoItemModel) => {
        todoItem.isComplete = checked;
      });
    };

    // 删除已完成项目
    let removeCompleteItems = () => {
      let index = props.todoList.length;
      while (index--) {
        if (props.todoList[index].isComplete) {
          props.todoList.splice(index, 1);
        }
      }
    };
    return {
      selectCount,
      isSelectAll,
      selectAllItems,
      removeCompleteItems,
    };
  },
});
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: $item-height;
  margin-top: 20px;
  padding: $item-padding;
  border: 1px $boder-color solid;
  border-radius: 5px;
}
</style>
